package LC;

/**
 * https://leetcode.com/problems/partition-list/description/
 * Given a linked list and a value x,
 * partition it such that all nodes less than x come before nodes greater than or equal to x.
 * You should preserve the original relative order of the nodes in each of the two partitions.
 * For example,
 * Given 1->4->3->2->5->2 and x = 3,
 * return 1->2->2->4->3->5.
 */
public class LC_086_PartitionList_LinkedList {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(4);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(2);
        head.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next = new ListNode(2);
        int x = 3;
        ListNode h = Solution.partition(head, x);
        ListNode cur = h;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    static class Solution {
        static ListNode partition(ListNode head, int x) {
            ListNode preHead = new ListNode(0);
            preHead.next = head;
            ListNode pre = preHead;
            ListNode cur = head;
            ListNode insertPos = null;
            while (cur != null) {
                //定位需要插入的位置;
                if (cur.val >= x && insertPos == null) insertPos = pre;
                //插入操作;
                if (cur.val < x && insertPos != null) {
                    pre.next = pre.next.next;
                    cur.next = insertPos.next;
                    insertPos.next = cur;
                    insertPos = insertPos.next;
                    cur = pre.next;
                    continue;
                }
                pre = pre.next;
                cur = cur.next;
            }
            return preHead.next;
        }
    }
}
